import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useCustomerStore = defineStore('customer', () => {
  // 状态
  const customers = ref([])
  const currentCustomer = ref(null)
  const isLoading = ref(false)
  const totalCount = ref(0)

  /**
   * 获取客户列表
   * @param {Object} params 查询参数
   * @param {number} params.page 页码
   * @param {number} params.pageSize 每页数量
   * @param {string} [params.keyword] 搜索关键词
   * @param {string} [params.status] 客户状态
   * @param {string} [params.customerType] 客户类型
   * @returns {Promise<{items: Array, total: number}>} 客户列表和总数
   */
  const getCustomers = async (params) => {
    try {
      isLoading.value = true
      // 这里应该调用API获取客户列表
      // const response = await api.getCustomers(params)
      // customers.value = response.data.items
      // totalCount.value = response.data.total
      
      // 模拟API调用
      // 生成模拟数据
      const mockCustomers = []
      for (let i = 0; i < params.pageSize; i++) {
        const index = (params.page - 1) * params.pageSize + i
        if (index >= 100) break // 最多100条数据
        
        mockCustomers.push({
          id: `${index + 1}`,
          customerCode: `C${String(index + 1).padStart(5, '0')}`,
          customerName: `客户${index + 1}`,
          shortName: `客户${index + 1}`,
          customerType: ['U8', '电池箔', '铜铝复合', '纯铝', '再生铝'][index % 5],
          responsiblePerson: `负责人${index + 1}`,
          responsiblePhone: `1381234${String(index + 1).padStart(4, '0')}`,
          responsibleEmail: `contact${index + 1}@example.com`,
          address: `地址${index + 1}`,
          contacts: [
            {
              id: `contact-${index + 1}-1`,
              contactName: `联系人${index + 1}-1`,
              contactPhone: `1391234${String(index + 1).padStart(4, '0')}`,
              email: `contact${index + 1}-1@example.com`,
              position: '经理',
              status: 'normal'
            }
          ],
          status: ['pre-sales', 'normal', 'deleted'][index % 3],
          remark: `备注${index + 1}`,
          createTime: new Date().toISOString(),
          updateTime: new Date().toISOString()
        })
      }
      
      customers.value = mockCustomers
      totalCount.value = 100
      
      return {
        items: customers.value,
        total: totalCount.value
      }
    } catch (error) {
      console.error('获取客户列表失败', error)
      return {
        items: [],
        total: 0
      }
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 获取客户详情
   * @param {string} id 客户ID
   * @returns {Promise<Object|null>} 客户详情
   */
  const getCustomerById = async (id) => {
    try {
      isLoading.value = true
      // 这里应该调用API获取客户详情
      // const response = await api.getCustomerById(id)
      // currentCustomer.value = response.data
      
      // 模拟API调用
      const index = parseInt(id) - 1
      currentCustomer.value = {
        id,
        customerCode: `C${String(index + 1).padStart(5, '0')}`,
        customerName: `客户${index + 1}`,
        shortName: `客户${index + 1}`,
        customerType: ['U8', '电池箔', '铜铝复合', '纯铝', '再生铝'][index % 5],
        responsiblePerson: `负责人${index + 1}`,
        responsiblePhone: `1381234${String(index + 1).padStart(4, '0')}`,
        responsibleEmail: `contact${index + 1}@example.com`,
        address: `地址${index + 1}`,
        contacts: [
          {
            id: `contact-${index + 1}-1`,
            contactName: `联系人${index + 1}-1`,
            contactPhone: `1391234${String(index + 1).padStart(4, '0')}`,
            email: `contact${index + 1}-1@example.com`,
            position: '经理',
            status: 'normal'
          }
        ],
        status: ['pre-sales', 'normal', 'deleted'][index % 3],
        remark: `备注${index + 1}`,
        createTime: new Date().toISOString(),
        updateTime: new Date().toISOString()
      }
      
      return currentCustomer.value
    } catch (error) {
      console.error('获取客户详情失败', error)
      return null
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 创建客户
   * @param {Object} customer 客户信息
   * @returns {Promise<Object|null>} 创建的客户
   */
  const createCustomer = async (customer) => {
    try {
      isLoading.value = true
      // 这里应该调用API创建客户
      // const response = await api.createCustomer(customer)
      // return response.data
      
      // 模拟API调用
      const newCustomer = {
        ...customer,
        id: `${customers.value.length + 1}`,
        createTime: new Date().toISOString(),
        updateTime: new Date().toISOString()
      }
      
      customers.value.unshift(newCustomer)
      totalCount.value++
      
      return newCustomer
    } catch (error) {
      console.error('创建客户失败', error)
      return null
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 更新客户
   * @param {string} id 客户ID
   * @param {Object} customer 客户信息
   * @returns {Promise<Object|null>} 更新后的客户
   */
  const updateCustomer = async (id, customer) => {
    try {
      isLoading.value = true
      // 这里应该调用API更新客户
      // const response = await api.updateCustomer(id, customer)
      // return response.data
      
      // 模拟API调用
      const index = customers.value.findIndex(c => c.id === id)
      if (index !== -1) {
        customers.value[index] = {
          ...customers.value[index],
          ...customer,
          updateTime: new Date().toISOString()
        }
        return customers.value[index]
      }
      return null
    } catch (error) {
      console.error('更新客户失败', error)
      return null
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 删除客户
   * @param {string} id 客户ID
   * @returns {Promise<boolean>} 是否删除成功
   */
  const deleteCustomer = async (id) => {
    try {
      isLoading.value = true
      // 这里应该调用API删除客户
      // await api.deleteCustomer(id)
      
      // 模拟API调用
      const index = customers.value.findIndex(c => c.id === id)
      if (index !== -1) {
        customers.value.splice(index, 1)
        totalCount.value--
      }
      
      return true
    } catch (error) {
      console.error('删除客户失败', error)
      return false
    } finally {
      isLoading.value = false
    }
  }

  return {
    customers,
    currentCustomer,
    isLoading,
    totalCount,
    getCustomers,
    getCustomerById,
    createCustomer,
    updateCustomer,
    deleteCustomer
  }
})